package servlet;

import entity.Product;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 石小俊
 */
@WebServlet("*.product")
public class ProductServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String path = req.getServletPath();
        switch (path) {
            case "/findAll.product":
                findAll(req, resp);
                break;
            case "/findById.product":
                findById(req, resp);
                break;
        }


    }

    protected void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        String id = req.getParameter("id");
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Product product = null;
        try {
            // 根据主键查询员工信息
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,price ")
                    .append(" from t_product ")
                    .append(" where id = ? ")
                    .toString();
            ps = conn.prepareStatement(sql);
            ps.setInt(1, Integer.parseInt(id));
            rs = ps.executeQuery();
            if (rs.next()) {
                product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
                // 此时已经查询到数据并封装成了Java对象
                // 由于需要将该数据传递到前台,因此需要使用跨语言的数据格式。
                // 例如:JSON、XML
                // 由于JSON解析比较简单,因此一般在开发中建议使用JSON来传输数据
                // 需要将Java对象转换成JSON格式的字符串
                // String productJson = "{'id':" + product.getId() + ",'name':'" + product.getName() + "','price':" + product.getPrice() + "}";
                // 可以使用JSON工具来帮助开发者将Java对象转换成JSON格式的字符串
                // 此处以apache提供的依赖为例
                // 在JSON工具类中提供了一个JSONObject,该对象表示一个JSON对象
                // JSONObject.fromObject(Object obj):将一个Java对象obj转换成JSONObject
                // 在JSONObject中提供了转换成字符串的方法
                JSONObject jsonObject = JSONObject.fromObject(product);
                String productJson = jsonObject.toString();
                out.println(productJson);
                return;

                // 除了JSONObject,还提供了JSONArray
                // JSONArray用法与JSONObject完全一致,只是专门用来将Java中的集合/数组转换成JSON对象数组
                // JSONArray jsonArray = JSONArray.fromObject(Object obj)
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("未找到驱动");
        } catch (SQLException e) {
            throw new RuntimeException("数据访问异常");
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放连接失败");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放状态集失败");
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放结果集失败");
                }
            }
        }
    }

    protected void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Product> products = new ArrayList<>();
        try {
            // 根据主键查询员工信息
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/shop?useUnicode=true&characterEncoding=utf-8", "root", "root");
            String sql = new StringBuffer()
                    .append(" select id,name,price ")
                    .append(" from t_product ")
                    .toString();
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                Product product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setPrice(rs.getDouble("price"));
                products.add(product);
            }
            req.setAttribute("products", products);
//            req.getRequestDispatcher("/jsp/list.jsp").forward(req, resp);
            req.getRequestDispatcher("/jquery/list.jsp").forward(req, resp);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("未找到驱动");
        } catch (SQLException e) {
            throw new RuntimeException("数据访问异常");
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放连接失败");
                }
            }
            if (ps != null) {
                try {
                    ps.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放状态集失败");
                }
            }
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException("释放结果集失败");
                }
            }
        }
    }
}
